/************************************************
* 描述
  * File: threadpool.h
  * Author: qijiangyong@mozihealthcare.cn
  * Date: 2025-08-13
  * Update:
  ***********************************************/
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <QObject>
#include <QThreadPool>
#include <common/asyc/taskqueue.h>
class CXI_COMMON_EXPORT ThreadPool : public QObject
{
	Q_OBJECT
public:
	static ThreadPool* instance()
	{
		static ThreadPool pool;
		return &pool;
	}
	// 添加任务
	template <typename F>
	void addTask(F&& f, int id,
				 task_priority priority = task_priority::TP_NORMAL)
	{
		auto task = new Task<std::decay_t<F>>(std::forward<F>(f), id, priority);

		connect(task->proxy(), &TaskProxy::taskFinished,
				this, &ThreadPool::finished, Qt::QueuedConnection);
		connect(task->proxy(), &TaskProxy::taskError, this,
				[=](int id, const QString& err){
			qWarning() << QString("[%1]task exec err:%2").arg(id).arg(err);
			emit taskExit();
		}, Qt::QueuedConnection);
		m_taskQueue.enqueue(task);
	}
	// 获取一条任务
	QRunnable* getOneTask(void);
	// 任务数目
	int taskSize(void);
	// 是否为空
	bool isEmpty(void);
	// 开始执行任务
	void runTask(void);

	~ThreadPool();

	signals:
		void finished(int, const QVariant&);
		void taskExit();

private slots:
	void taskFinished(int id, const QVariant& v);

private:
	ThreadPool();

	void _init(void);
	bool _hasOk(void);

	void _exit();
private:
	QThreadPool* m_threadPool;      // 线程池
	TaskQueue m_taskQueue;          // 任务队列
	QAtomicInt m_runningTasks{0};   // 原子计数，线程安全

};


#endif//THREADPOOL_H
